/*
 * 针对小学图书馆的接口对象
 */
package com.smforj.ssm.modules.api.controller;

import java.util.List;

import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smforj.ssm.frame.core.enums.RouterMapping;
import com.smforj.ssm.frame.core.web.controller.BaseControllerSupportImpl;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.modules.lib.domain.CheckInResponse;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.FeePaidResponse;
import com.smforj.ssm.modules.lib.domain.ItemResponse;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.PatronResponse;
import com.smforj.ssm.modules.lib.domain.RFIDRequest;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.Tag;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.lib.service.BookInfoService;
import com.smforj.ssm.modules.lib.service.LibraryService;
import com.smforj.ssm.modules.sys.service.SysReaderService;
 

/****
 * 中小学图书馆专用公共处理Api接口Controller
 *
 * @author Haijun Gao 
 * @date 2017-4-28 下午4:10:27
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
@RouterMapping("")
@Controller
@RequestMapping("/eslibrary/api")
@Scope(value = "singleton")
public class ESlibraryController extends BaseControllerSupportImpl {

    private static final Log ELOG = LogFactory.getLog(ESlibraryController.class);

    @Autowired
    @Qualifier("eslibraryService")
    private LibraryService libraryService;

    @Autowired
    @Qualifier("sysReaderService")
    private SysReaderService readerService;

    @Autowired
    @Qualifier("sysBookInfoService")
    private BookInfoService sysBookInfoService; 

    /***
     * 检测网络是否正常
     * @param id 测试ID
     * @return 测试结果
     * @date 2017-8-10 下午8:14:01
     */
    @RequestMapping(value = {"/status/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<String> getStatus(@PathVariable("id") String id) {
        DataResult<String> result = new DataResult<String>();  
        long startTime = System.currentTimeMillis(); //获取当前时间
        System.out.print("begin：" + startTime);
        //doSomeThing();   //要运行的java程序
        result.addOK(libraryService.testStatus(id),"");
        long endTime = System.currentTimeMillis();
        System.out.print("程序运行时间：" + (endTime - startTime) + "ms");
       
        return result;
    }

    /****
     * 客户端与服务器登陆接口,token未使用
     * @param request 登陆请求
     * @return 登陆结果
     * @date 2017-6-30 下午2:26:29
     */
    @RequestMapping(value = {"/login"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<PatronResponse> login(@RequestBody LibraryRequest<String> request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("login reader id:  " + request.getSzUserId());
        }
        //返回读者信息
        DataResult<PatronResponse> result = new DataResult<PatronResponse>();
        PatronResponse patron = getReaderInfo(request.getLoginType().toString(), request.getSzUserId());
        if (patron.getStatus() == 0) {
            result.addError(patron.getMessage());
        } else {
            result.addOK("", patron);
        }
        //前期为显示信息，后期将删除
        return result;
    }  

    /****
     * 获取读者信息
     * @param type 类型
     * @param id 读者id
     * @return 读者完整信息
     * @date 2017-12-27 下午12:45:53
     */
    @RequestMapping(value = {"/reader/{type}/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<PatronResponse> getReader(@PathVariable("type") String type, @PathVariable("id") String id) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("getReader type: " + type + " id " + id);
        }
        //返回读者信息
        DataResult<PatronResponse> result = new DataResult<PatronResponse>();
        PatronResponse patron = getReaderInfo(type, id);
        if (patron.getStatus() == 0) {
            result.addError(patron.getMessage());
        } else {
            result.addOK("", patron);
        }
        //前期为显示信息，后期将删除
        return result;
    }

    /***
     * 获取用户信息
     * @param logintype 登陆类型
     * @param id 用户ID
     * @return 登陆结果
     * @date 2017-8-12 上午11:52:59
     */
    private PatronResponse getReaderInfo(String logintype, String id) {
        PatronResponse patron = new PatronResponse();
        SysReader query = new SysReader();
        if (logintype.equalsIgnoreCase("RFID")) {
            query.setRfidCardNum(id);
        } else {
            query.setIdCardNum(id);
        }
        try {
            query = readerService.queryOne(query);
            if (null != query) {
                LibraryRequest<String> request = new LibraryRequest<String>();
                request.setSzUserId(query.getCampusCardNum());
                patron = libraryService.getReader(request);

                patron.setCampusCardNum(query.getCampusCardNum());
                patron.setRfid(query.getRfidCardNum());
                patron.setCardid(query.getIdCardNum());
            } else {
                patron.setStatus(0);
                patron.setMessage("无该读者信息");
            }
        } catch (Exception ex) {
            ELOG.error("查询读者信息异常：" + ex.getMessage());
            patron.setStatus(0);
            patron.setMessage("查询异常");
        }
        return patron;
    }

    /****
     * 获取图书关系信息
     * @param id 图书编码
     * @return 图书关系信息
     * @date 2017-12-27 下午12:46:15
     */
    @RequestMapping(value = {"/bookrelation/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<ItemResponse> getBookRelation(@PathVariable("id") String id) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("getBookRelation id: " + id);
        }
        DataResult<ItemResponse> result = new DataResult<ItemResponse>();
        ItemResponse item = new ItemResponse();
        try {
            SysBookVo sBook = sysBookInfoService.selectBookByRfid(id);
            if (null != sBook) {
                item.setRfid(id);
                item.setBarcode(sBook.getBarcode());
                result.addOK("", item);
            } else {
                item.setStatus(0);
                item.setMessage("无该图书");
                result.addError(item.getMessage());
            }
        } catch (Exception ex) {
            ELOG.error("查询图书信息异常：" + ex.getMessage());
            item.setStatus(0);
            item.setMessage("查询异常");
            result.addError(item.getMessage());
        }
        return result;
    }

    /****
     * 获取图书信息
     * @param id 图书RFID
     * @return 图书信息
     * @date 2017-12-27 下午12:47:05
     */
    @RequestMapping(value = {"/book/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<ItemResponse> getBook(@PathVariable("id") String id) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("getBook id: " + id);
        }
        DataResult<ItemResponse> result = new DataResult<ItemResponse>();
        ItemResponse item = new ItemResponse();
        try {
            SysBookVo sBook = sysBookInfoService.selectBookByRfid(id);
            if (null != sBook) {
                LibraryRequest<String> request = new LibraryRequest<String>(); 
                request.setData(sBook.getBarcode());
                item = libraryService.getBookInfo(request);
                item.setBarcode(sBook.getBarcode());
                item.setRfid(sBook.getRfid());
                if (item.getStatus() == 0) {
                    result.addError(item.getMessage());
                } else {
                    result.addOK("", item);
                }
            } else {
                item.setStatus(0);
                item.setMessage("无该图书");
                result.addError(item.getMessage());
            }
        } catch (Exception ex) {
            ELOG.error("查询图书信息异常：" + ex.getMessage());
            item.setStatus(0);
            item.setMessage("查询异常");
            result.addError(item.getMessage());
        }
        return result;
    }

    /****
     * 检测图书是否借还
     * @param request 查询请求
     * @return 图书状态结果
     * @date 2017-6-30 下午2:26:29
     */
    @RequestMapping(value = {"/book/status"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<Tag>> checkBookStatus(@RequestBody RFIDRequest request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("checkBookStatus ip: " + request.getIp());
        }
        //返回读者信息
        DataResult<List<Tag>> result = new DataResult<List<Tag>>();  
        result.addOK("", libraryService.cBookStatus(request)); 
        return result;
    }  

    /***
     * 借阅
     * @param request 借阅请求
     * @return 借阅结果
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/checkout"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> doCheckout(@RequestBody LibraryRequest<String[]> request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("doCheckout ip: " + request.getSzUserId());
        }
        //todo
        SysReader sysReader = new SysReader();
        sysReader.setId(request.getSzUserId());
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
        result.addOK("", libraryService.doCheckout(request));
        //sysRecordService.saveRecord(RecordType.BORROW, result.getData(), sysReader);
        return result;
    }


    /***
     * 归还
     * @param request 归还请求
     * @return 归还结果
     */
    @RequestMapping(value = {"/checkin"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckInResponse>> doCheckin(@RequestBody LibraryRequest<String[]> request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("doCheckin ip: " + request.getSzUserId());
        }
        DataResult<List<CheckInResponse>> result = new DataResult<List<CheckInResponse>>();
        result.addOK("", libraryService.doCheckin(request));
        //sysRecordService.saveRecord(RecordType.RETURN, result.getData());
        return result;
    } 

    /***
     * 续借
     * @param request 续借请求
     * @return 续借结果
     */
    @RequestMapping(value = {"/renew"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> doRenew(@RequestBody LibraryRequest<String[]> request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("doRenew ip: " + request.getSzUserId());
        }
        //todo
        SysReader sysReader = new SysReader();
        sysReader.setId(request.getSzUserId());
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
        result.addOK("", libraryService.doRenew(request));
        //sysRecordService.saveRecord(RecordType.REVEW, result.getData(), sysReader);
        return result;
    }


    /***
     * Pay Fee
     * @param request 罚款请求
     * @return 罚款结果
     */
    @RequestMapping(value = {"/payfee"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<FeePaidResponse> doPayFee(@RequestBody LibraryRequest<String> request) {
        if (ELOG.isDebugEnabled()) {
            ELOG.debug("doPayFee ip: " + request.getSzUserId());
        }
        DataResult<FeePaidResponse> result = new DataResult<FeePaidResponse>();
        result.addOK("", libraryService.doPayFee(request));
        return result;
    }
}
